# 文件名: app/routes/pages.py
import os
import sys
import urllib.parse
import uuid
from typing import Optional

from fastapi import APIRouter, Request, Depends, Query
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
import json
from datetime import datetime
from app.models.database import get_db, MonitoredUser, Video, SystemSetting, SchedulerTask, HotVideo
from app.utils.logging_config import logger

router = APIRouter()


# 获取应用根路径
def get_app_root():
    if getattr(sys, 'frozen', False):
        # 打包环境
        return os.path.dirname(sys.executable)
    else:
        # 开发环境
        return os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


# 设置模板路径
APP_ROOT = get_app_root()
templates = Jinja2Templates(directory=os.path.join(APP_ROOT, "app", "templates"))


# 用户列表页面
@router.get("/users")
async def users_page(
        request: Request,
        page: int = Query(1, ge=1),
        per_page: int = Query(10, ge=5, le=100),
        platform: str = Query(None),
        category: str = None,
        search: str = Query(None),
        db: Session = Depends(get_db)
):
    # 构建查询
    query = db.query(MonitoredUser)

    # 应用搜索过滤
    if search:
        query = query.filter(MonitoredUser.username.like(f"%{search}%"))

    # 应用平台过滤
    if platform:
        query = query.filter(MonitoredUser.platform == platform)

    # 应用分类过滤
    if category:
        query = query.filter(MonitoredUser.category == category)

    # 获取总记录数
    total = query.count()

    # 应用分页
    query = query.order_by(MonitoredUser.created_at.desc())
    query = query.offset((page - 1) * per_page).limit(per_page)

    # 执行查询
    users = query.all()

    users_data = []
    for user in users:
        profile_info = {}
        try:
            profile_info = json.loads(user.profile_info)
        except:
            pass

        profile_pic = ""
        if user.platform == "tiktok":
            if "avatar_thumb" in profile_info and "url_list" in profile_info.get("avatar_thumb", {}):
                profile_pic = profile_info.get("avatar_thumb", {}).get("url_list", [""])[0]
        elif user.platform == "douyin":
            if "cover_and_head_image_info" in profile_info:
                cover_info = profile_info.get("cover_and_head_image_info", {})
                profile_covers = cover_info.get("profile_cover_list", [])
                if profile_covers and "cover_url" in profile_covers[0]:
                    url_list = profile_covers[0]["cover_url"].get("url_list", [])
                    if url_list:
                        profile_pic = url_list[0]
        elif user.platform == "instagram":
            profile_pic = profile_info.get("profile_pic_url", "")
        elif user.platform == "kuaishou":
            profile_pic = profile_info.get("headurl", "")

        users_data.append({
            "id": user.id,
            "platform": user.platform,
            "username": user.username,
            "profile_pic": profile_pic,
            "category": user.category,
            "last_video_count": user.last_video_count,
            "is_open": user.is_open,
            "last_checked": user.last_checked.strftime("%Y-%m-%d %H:%M:%S") if user.last_checked else "",
            "created_at": user.created_at.strftime("%Y-%m-%d %H:%M:%S") if user.created_at else ""
        })

    # 获取所有唯一分类用于下拉框
    all_categories = db.query(MonitoredUser.category) \
        .filter(MonitoredUser.category != None) \
        .filter(MonitoredUser.category != "") \
        .distinct() \
        .all()
    categories = [cat[0] for cat in all_categories]

    # 构建分页信息
    pagination = {
        "total": total,
        "page": page,
        "per_page": per_page,
        "pages": (total + per_page - 1) // per_page
    }

    return templates.TemplateResponse("users.html", {
        "request": request,
        "users": users_data,
        "pagination": pagination,
        "platform": platform,
        "category": category,  # 传递分类到模板
        "categories": categories,  # 传递所有可用分类到模板
        "search": search
    })


# 用户详情页面
@router.get("/users/{user_id}")
async def user_detail(
        request: Request,
        user_id: int,
        page: int = Query(1, ge=1),
        per_page: int = Query(6, ge=3, le=30),
        db: Session = Depends(get_db)
):
    user = db.query(MonitoredUser).filter(MonitoredUser.id == user_id).first()
    if not user:
        return templates.TemplateResponse("error.html", {"request": request, "message": "用户不存在"})

    profile_info = {}
    try:
        profile_info = json.loads(user.profile_info)
    except:
        pass

    # 获取用户头像
    profile_pic = ""
    if user.platform == "tiktok":
        if "avatar_thumb" in profile_info:
            profile_pic = profile_info.get("avatar_thumb", {}).get("url_list", [""])[0]
    elif user.platform == "douyin":
        # 从cover_and_head_image_info中提取头像URL
        if "cover_and_head_image_info" in profile_info:
            cover_info = profile_info.get("cover_and_head_image_info", {})
            profile_covers = cover_info.get("profile_cover_list", [])
            if profile_covers and "cover_url" in profile_covers[0]:
                url_list = profile_covers[0]["cover_url"].get("url_list", [])
                if url_list:
                    profile_pic = url_list[0]
    elif user.platform == "instagram":
        profile_pic = profile_info.get("profile_pic_url", "")
    elif user.platform == "kuaishou":
        profile_pic = profile_info.get("headurl", "")

    # 获取用户简介
    signature = ""
    if user.platform == "tiktok":
        signature = profile_info.get("signature", "")
    elif user.platform == "douyin":
        signature = profile_info.get("signature", "")
    elif user.platform == "instagram":
        signature = profile_info.get("biography", "")
    elif user.platform == "kuaishou":
        signature = profile_info.get("user_text", "")

    # 获取用户视频并分页
    video_query = db.query(Video).filter(Video.user_id == user_id)
    total_videos = video_query.count()

    video_query = video_query.order_by(Video.created_at.desc())
    video_query = video_query.offset((page - 1) * per_page).limit(per_page)

    videos = video_query.all()

    videos_data = []
    for video in videos:
        # 检查video.local_path是否为空
        if video.local_path:
            encoded_path = urllib.parse.quote(video.local_path)
        else:
            encoded_path = ""  # 如果为空，则不进行编码

        videos_data.append({
            "id": video.id,
            "title": video.title,
            "local_path": encoded_path,
            "download_status": video.download_status,
            "last_download_url": video.last_download_url,
            "created_at": video.created_at.strftime("%Y-%m-%d %H:%M:%S") if video.created_at else ""
        })

    # 构建分页信息
    pagination = {
        "total": total_videos,
        "page": page,
        "per_page": per_page,
        "pages": (total_videos + per_page - 1) // per_page
    }

    user_data = {
        "id": user.id,
        "platform": user.platform,
        "username": user.username,
        "sec_uid": user.sec_uid,
        "profile_pic": profile_pic,
        "signature": signature,
        "last_video_count": user.last_video_count,
        "last_checked": user.last_checked.strftime("%Y-%m-%d %H:%M:%S") if user.last_checked else "",
        "created_at": user.created_at.strftime("%Y-%m-%d %H:%M:%S") if user.created_at else ""
    }

    return templates.TemplateResponse("user_detail.html", {
        "request": request,
        "user": user_data,
        "videos": videos_data,
        "pagination": pagination,
        "total_videos": total_videos
    })


# 视频列表页面
@router.get("/videos")
async def videos_page(
        request: Request,
        page: int = Query(1, ge=1),
        per_page: int = Query(10, ge=5, le=100),
        user_id: int = Query(None),
        platform: str = Query(None),
        status: str = Query(None),
        search: str = Query(None),
        start_date: str = Query(None),  # 起始日期
        end_date: str = Query(None),  # 结束日期
        db: Session = Depends(get_db)
):
    query = db.query(Video)

    # 获取用户信息（如果指定了用户ID）
    username = None
    if user_id:
        query = query.filter(Video.user_id == user_id)
        user = db.query(MonitoredUser).filter(MonitoredUser.id == user_id).first()
        if user:
            username = user.username

    if platform:
        query = query.filter(Video.platform == platform)

    if status:
        query = query.filter(Video.download_status == status)

    if search:
        query = query.filter(Video.title.ilike(f"%{search}%"))

    if start_date:
        query = query.filter(Video.download_at >= datetime.strptime(start_date, "%Y-%m-%d"))

    if end_date:
        query = query.filter(Video.download_at <= datetime.strptime(end_date, "%Y-%m-%d"))

    # 获取总记录数
    total = query.count()

    # 获取下载总数
    total_download_count = query.filter(Video.download_status == "downloaded").count()

    # 应用分页
    query = query.order_by(Video.created_at.desc())
    query = query.offset((page - 1) * per_page).limit(per_page)

    # 执行查询
    videos = query.all()

    videos_data = []
    for video in videos:
        # 获取用户信息
        user = db.query(MonitoredUser).filter(MonitoredUser.id == video.user_id).first()
        username_display = user.username if user else "未知用户"

        # 检查video.local_path是否为空
        if video.local_path:
            encoded_path = urllib.parse.quote(video.local_path)
        else:
            encoded_path = ""  # 如果为空，则不进行编码

        videos_data.append({
            "id": video.id,
            "user_id": video.user_id,
            "username": username_display,
            "platform": video.platform,
            "title": video.title,
            "local_path": encoded_path,
            "download_status": video.download_status,
            "last_download_url": video.last_download_url,
            "created_at": video.created_at.strftime("%Y-%m-%d %H:%M:%S") if video.created_at else "",
            "download_at": video.download_at.strftime("%Y-%m-%d %H:%M:%S") if video.download_at else "",
        })

    # 构建分页信息
    pagination = {
        "total": total,
        "page": page,
        "per_page": per_page,
        "pages": (total + per_page - 1) // per_page,
    }

    return templates.TemplateResponse("videos.html", {
        "request": request,
        "videos": videos_data,
        "pagination": pagination,
        "user_id": user_id,
        "username": username,
        "platform": platform,
        "start_date": start_date,
        "end_date": end_date,
        "status": status,
        "total_download_count": total_download_count,  # 返回下载总数
        "search": search
    })


# 播放视频页面
@router.get("/play/{video_id}")
async def play_video(request: Request, video_id: int, db: Session = Depends(get_db)):
    video = db.query(Video).filter(Video.id == video_id).first()
    if not video:
        return templates.TemplateResponse("error.html", {"request": request, "message": "视频不存在"})

    if video.download_status != "downloaded" or not video.local_path:
        return templates.TemplateResponse("error.html", {"request": request, "message": "视频未下载或下载失败"})

    # 获取用户信息
    user = db.query(MonitoredUser).filter(MonitoredUser.id == video.user_id).first()
    username = user.username if user else "未知用户"

    # 检查video.local_path是否为空
    if video.local_path:
        encoded_path = urllib.parse.quote(video.local_path)
    else:
        encoded_path = ""  # 如果为空，则不进行编码

    video_data = {
        "id": video.id,
        "user_id": video.user_id,
        "username": username,
        "platform": video.platform,
        "title": video.title,
        "local_path": encoded_path,
        "created_at": video.created_at.strftime("%Y-%m-%d %H:%M:%S") if video.created_at else "",
        "download_at": video.download_at.strftime("%Y-%m-%d %H:%M:%S") if video.created_at else "",
    }

    return templates.TemplateResponse("play_video.html", {"request": request, "video": video_data})


# 统计信息页面
@router.get("/stats")
async def stats_page(request: Request, db: Session = Depends(get_db)):
    # 获取平台统计
    platform_stats = {}
    for platform in ["tiktok", "douyin", "instagram", "kuaishou"]:
        user_count = db.query(MonitoredUser).filter(MonitoredUser.platform == platform).count()
        video_count = db.query(Video).filter(Video.platform == platform).count()
        downloaded_count = db.query(Video).filter(Video.platform == platform,
                                                  Video.download_status == "downloaded").count()
        failed_count = db.query(Video).filter(Video.platform == platform, Video.download_status == "failed").count()

        platform_stats[platform] = {
            "user_count": user_count,
            "video_count": video_count,
            "downloaded_count": downloaded_count,
            "failed_count": failed_count
        }

    # 获取总数统计
    total_users = db.query(MonitoredUser).count()
    total_videos = db.query(Video).count()
    downloaded_videos = db.query(Video).filter(Video.download_status == "downloaded").count()
    failed_videos = db.query(Video).filter(Video.download_status == "failed").count()

    stats = {
        "total_users": total_users,
        "total_videos": total_videos,
        "downloaded_videos": downloaded_videos,
        "failed_videos": failed_videos,
        "platforms": platform_stats
    }

    # 获取监控设置
    settings = db.query(SystemSetting).all()
    settings_data = []

    for setting in settings:
        settings_data.append({
            "key": setting.key,
            "value": setting.value,
            "description": setting.description,
            "updated_at": setting.updated_at.strftime("%Y-%m-%d %H:%M:%S") if setting.updated_at else ""
        })

    # 获取任务状态
    tasks = SchedulerTask.get_all_tasks(db)
    task_data = []

    for task in tasks:
        task_data.append({
            "id": task.id,
            "task_id": task.task_id,
            "task_name": task.task_name,
            "status": task.status,
            "last_run_at": task.last_run_at.strftime("%Y-%m-%d %H:%M:%S") if task.last_run_at else "从未运行",
            "next_run_at": task.next_run_at.strftime("%Y-%m-%d %H:%M:%S") if task.next_run_at else "未计划",
            "last_result": task.last_result or "",
            "updated_at": task.updated_at.strftime("%Y-%m-%d %H:%M:%S") if task.updated_at else ""
        })

    return templates.TemplateResponse(
        "stats.html", {
            "request": request,
            "stats": stats,
            "settings": settings_data,
            "tasks": task_data
        })


@router.get("/settings")
async def settings_page(request: Request, db: Session = Depends(get_db)):
    settings = db.query(SystemSetting).all()
    settings_data = []

    for setting in settings:
        settings_data.append({
            "key": setting.key,
            "value": setting.value,
            "description": setting.description,
            "updated_at": setting.updated_at.strftime("%Y-%m-%d %H:%M:%S") if setting.updated_at else ""
        })

    return templates.TemplateResponse("settings.html", {
        "request": request,
        "settings": settings_data
    })


# 错误页面
@router.get("/error")
async def error_page(request: Request, message: str = "发生未知错误"):
    return templates.TemplateResponse("error.html", {"request": request, "message": message})


# 进度页面
@router.get("/progress")
async def progress_page(
        request: Request,
        client_id: Optional[str] = None
):
    # 如果未提供客户端ID，生成一个新的
    if not client_id:
        client_id = str(uuid.uuid4())

    return templates.TemplateResponse("progress.html", {
        "request": request,
        "client_id": client_id
    })


# 热门视频页面
@router.get("/hot-videos")
async def hot_videos_page(
        request: Request,
        page: int = Query(1, ge=1),
        per_page: int = Query(12, ge=4, le=100),
        platform: str = Query("douyin"),
        category: str = Query(None),
        sort_by: str = Query("rank"),  # 新增排序字段
        sort_order: str = Query("asc"),  # 新增排序顺序
        start_date: str = Query(None),  # 新增开始日期
        end_date: str = Query(None),  # 新增结束日期
        db: Session = Depends(get_db)
):
    # 构建查询
    query = db.query(HotVideo)

    # 应用平台过滤
    if platform:
        query = query.filter(HotVideo.platform == platform)

    # 应用分类过滤
    if category:
        query = query.filter(HotVideo.category == category)

    # 应用日期过滤 - 使用发布时间字段
    if start_date:
        try:
            start_datetime = datetime.now().strptime(start_date, "%Y-%m-%d")
            query = query.filter(HotVideo.publish_time >= start_datetime)
        except ValueError:
            logger.warning(f"无效的开始日期格式: {start_date}")

    if end_date:
        try:
            # 将结束日期设置为当天的23:59:59，以包含整天
            end_datetime = datetime.now().strptime(end_date, "%Y-%m-%d")
            end_datetime = end_datetime.replace(hour=23, minute=59, second=59)
            query = query.filter(HotVideo.publish_time <= end_datetime)
        except ValueError:
            logger.warning(f"无效的结束日期格式: {end_date}")

    # 获取总记录数
    total = query.count()

    # 应用排序
    if sort_by == "publish_time":
        # 按发布时间排序
        if sort_order.lower() == "desc":
            query = query.order_by(HotVideo.publish_time.desc())
        else:
            query = query.order_by(HotVideo.publish_time.asc())
    elif sort_by == "play_count":
        # 按播放次数排序
        if sort_order.lower() == "desc":
            query = query.order_by(HotVideo.play_count.desc())
        else:
            query = query.order_by(HotVideo.play_count.asc())
    elif sort_by == "like_count":
        # 按点赞次数排序
        if sort_order.lower() == "desc":
            query = query.order_by(HotVideo.like_count.desc())
        else:
            query = query.order_by(HotVideo.like_count.asc())
    else:
        # 默认按排名排序
        if sort_order.lower() == "desc":
            query = query.order_by(HotVideo.rank.desc(), HotVideo.created_at.desc())
        else:
            query = query.order_by(HotVideo.rank.asc(), HotVideo.created_at.desc())

    # 应用分页
    query = query.offset((page - 1) * per_page).limit(per_page)

    # 执行查询
    videos = query.all()

    # 格式化视频数据
    videos_data = []
    for video in videos:
        # 格式化视频时长
        duration_str = ""
        if video.duration:
            minutes = video.duration // 60000
            seconds = (video.duration % 60000) // 1000
            duration_str = f"{minutes}:{seconds:02d}"

        # 检查video.local_path是否为空
        if video.local_path:
            encoded_path = urllib.parse.quote(video.local_path)
        else:
            encoded_path = ""  # 如果为空，则不进行编码

        videos_data.append({
            "id": video.id,
            "platform": video.platform,
            "video_id": video.video_id,
            "title": video.title,
            "cover_url": video.cover_url,
            "video_url": video.video_url,
            "duration": duration_str,
            "author": video.author,
            "avatar_url": video.avatar_url,
            "fans_count": video.fans_count,
            "play_count": video.play_count,
            "like_count": video.like_count,
            "publish_time": video.publish_time.strftime("%Y-%m-%d %H:%M") if video.publish_time else "",
            "local_path": encoded_path,
            "download_status": video.download_status,
            "rank": video.rank,
            "is_favorite": video.is_favorite,
            "is_selected": video.is_selected
        })

    # 获取所有分类
    categories = db.query(HotVideo.category) \
        .filter(HotVideo.category != None) \
        .filter(HotVideo.category != "") \
        .distinct() \
        .all()
    categories = [cat[0] for cat in categories]

    # 构建分页信息
    pagination = {
        "total": total,
        "page": page,
        "per_page": per_page,
        "pages": (total + per_page - 1) // per_page
    }

    # 构建可选的每页显示数量列表
    per_page_options = [12, 24, 36, 48, 60]

    # 构建排序选项
    sort_options = [
        {"value": "rank", "label": "热门排名", "current": sort_by == "rank"},
        {"value": "publish_time", "label": "发布时间", "current": sort_by == "publish_time"},
        {"value": "play_count", "label": "播放量", "current": sort_by == "play_count"},
        {"value": "like_count", "label": "点赞量", "current": sort_by == "like_count"}
    ]

    # 格式化日期显示
    formatted_start_date = None
    formatted_end_date = None

    if start_date:
        try:
            formatted_start_date = datetime.now().strptime(start_date, "%Y-%m-%d").strftime("%Y-%m-%d")
        except ValueError:
            pass

    if end_date:
        try:
            formatted_end_date = datetime.now().strptime(end_date, "%Y-%m-%d").strftime("%Y-%m-%d")
        except ValueError:
            pass

    return templates.TemplateResponse("hot_videos.html", {
        "request": request,
        "videos": videos_data,
        "pagination": pagination,
        "platform": platform,
        "category": category,
        "categories": categories,
        "sort_by": sort_by,
        "sort_order": sort_order,
        "per_page": per_page,
        "per_page_options": per_page_options,
        "sort_options": sort_options,
        "start_date": formatted_start_date,
        "end_date": formatted_end_date
    })


# 播放热门视频
@router.get("/hot-videos/{video_id}/play")
async def play_hot_video(
        request: Request,
        video_id: int,
        db: Session = Depends(get_db)
):
    video = db.query(HotVideo).filter(HotVideo.id == video_id).first()
    if not video:
        return templates.TemplateResponse("error.html", {"request": request, "message": "视频不存在"})

    if video.download_status != "downloaded" or not video.local_path:
        return templates.TemplateResponse("error.html", {"request": request, "message": "视频未下载或下载失败"})

    # 检查video.local_path是否为空
    if video.local_path:
        encoded_path = urllib.parse.quote(video.local_path)
    else:
        encoded_path = ""  # 如果为空，则不进行编码

    video_data = {
        "id": video.id,
        "platform": video.platform,
        "video_id": video.video_id,
        "title": video.title,
        "author": video.author,
        "avatar_url": video.avatar_url,
        "local_path": encoded_path,
        "publish_time": video.publish_time.strftime("%Y-%m-%d %H:%M") if video.publish_time else "",
        "play_count": video.play_count,
        "like_count": video.like_count
    }

    return templates.TemplateResponse("play_hot_video.html", {"request": request, "video": video_data})